package com.common.wx;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.common.util.ImageCompress;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class WxShareUtil {

    private static final String TAG = "SDK_Sample.Util";
    String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mulshare/";

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                //F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }

    /**
     * 分享单张图片
     *
     * @param bitmap
     * @param tag
     * @param type   哪种类型分享  SendMessageToWX.Req.WXSceneTimeline 朋友圈   SendMessageToWX.Req.WXSceneSession 朋友
     */
    public static void sharePicByBitMap(IWXAPI api, Context context, Bitmap bitmap, String tag, int app_Icon, int type) {
        WXImageObject imageObject = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, app_Icon);
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        msg.thumbData = bmpToByteArray(thumbBitmap, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();    //创建一个请求对象
        req.message = msg;  //把msg放入请求对象中
        req.scene = type;    //设置发送到朋友圈
        req.transaction = tag;  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        api.sendReq(req);   //如果调用成功微信,会返回true
    }

    /**
     * 分享网页
     *
     * @param api
     * @param context
     * @param url
     * @param title
     * @param description
     * @param type        type 哪种类型分享  SendMessageToWX.Req.WXSceneTimeline 朋友圈   SendMessageToWX.Req.WXSceneSession 朋友
     * @param app_Icon
     */
    public static void shareUrl(IWXAPI api, Context context, String url, String title, String description, int type, int app_Icon) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        Resources res = context.getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, app_Icon);
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
        msg.thumbData = bmpToByteArray(thumbBitmap, true);
        msg.description = description;
        msg.title = title;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type;
        req.transaction = "share";
        api.sendReq(req);
    }

    /**
     * 多图分享 多张图片分享其实就是上传本地图片功能，如qq就上传相册 发表动态 朋友圈  朋友圈仅支持单图分享
     * 每个均需要下载客户端
     * 0微信好友 1 朋友圈  2 手机qq好友 3 qq空间
     * @param context
     * @param type
     * @param list
     */
    private void shareMultBitmap(final Context context, final int type, final List<Bitmap> list) {
        if (!new File(storePath).exists()) {
            new File(storePath).mkdirs();
        }
        final List<String> urls = saveImgs(list);
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Intent intent = new Intent();
                ComponentName comp = null;
                if (type == 2 || type == 3) {
                    if (type == 2) {
                        comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                    } else {
                        comp = new ComponentName("com.qzone", "com.qzonex.module.operation.ui.QZonePublishMoodActivity");
                    }
                } else if (type == 0 || type == 1) {
                    if (type == 0) {
                        comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                    } else {
                        comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                    }
                }
                intent.setComponent(comp);
                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent.setType("image/*");
                final ArrayList<Uri> imageUris = new ArrayList<>();
                for (int i = 0; i < urls.size(); i++) {
                    if (type == 0 || type == 1) {
                        imageUris.add(getImageContentUri(context, new File(storePath + urls.get(i))));
                    } else {
                        imageUris.add(Uri.parse(storePath + urls.get(i)));
                    }
                }
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                intent.putExtra("Kdescription", "");
                context.startActivity(intent);
            }
        }).start();
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }

            cursor.close();
        }

        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }

        return uri;
    }

    private List<String> saveImgs(List<Bitmap> list) {
        List<String> urls = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String url = System.currentTimeMillis() + i + ".jpg";
            urls.add(ImageCompress.savePhoto(list.get(i), storePath, url));
        }
        return urls;
    }
}
